package textconvert;

import java.io.IOException;
import java.io.InputStream;

/**
 * 
 *@author Bing
 *@version 1.0 support two(begin/end) rule pattern  - xxx...xxxx <%$%>eeeee
 */
public class RuleFilterInputStream extends InputStream{	
	private static final int BUF_SIZE = 8192;
	private FormatRule rule_s = null;
	private FormatRule rule_e = null;
	private BufferedInputStream bufIn;
		
	/**
	 * xxxxxx<%$%>hhhhhhhh
	 * xxxxxx<%=$%>hhhhhhhh<%=$%>cccccc<%$%>eeee
	 * @param ins
	 * @param ruleText
	 */
	public RuleFilterInputStream(InputStream ins, byte[] ruleText){
		bufIn = new BufferedInputStream(ins, BUF_SIZE);		
		RulePattern ruleArr = new RulePattern(ruleText);
		rule_s = ruleArr.getRule(0);
		rule_e = ruleArr.getRule(1); 
	}
		
	public int read() throws IOException{	
		ConstByteArray lockByteArr;		
		if(rule_s != null){
			lockByteArr = bufIn.matchLock(rule_s);
			if(lockByteArr==null)
				return -1;
			bufIn.byteBufferUnlock(lockByteArr.length());
		}
		try{		
			lockByteArr = bufIn.byteBufferPeekLock(rule_e.length());
			if(lockByteArr.length()<1){
				return -1;
			}
			if(rule_e.matches(lockByteArr)){
				return -1;
			}
			return lockByteArr.byteAt(0);
		}finally{
			bufIn.byteBufferUnlock(1);
		}		
	}
	
	public void close(){
		if(bufIn!=null){
			bufIn.close();
			bufIn = null;
		}
	}
	
}
